package com.shi.yibanjia.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.entity.dto.UserLoginDto;
import com.shi.yibanjia.entity.po.User;
import com.shi.yibanjia.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDateTime;

import static com.shi.yibanjia.common.constant.RedisConstant.*;

@RestController
@RequestMapping("/app/index")
public class IndexController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody @Valid UserLoginDto userLoginDto) {
        // 1. 通过手机号查询redis中的验证码
        String codeInCache = (String) stringRedisTemplate.opsForValue().get(PHONE_CODE + userLoginDto.getPhone());
        // 2. 判断缓存中的验证码是否与用户提交的相同
        if (!userLoginDto.getCode().equals(codeInCache)) {
            return Result.fail("验证码错误");
        }
        // 3. 清除手机号验证码
        stringRedisTemplate.delete(PHONE_CODE + userLoginDto.getPhone());
        // 4. 判断数据库中存在该手机号，无需添加
        User user = userService.getByPhone(userLoginDto.getPhone());
        if (ObjUtil.isEmpty(user)) {
            user = new User();
            user.setPhone(userLoginDto.getPhone());
        }
        user.setLastLoginTime(LocalDateTime.now());
        userService.saveOrUpdate(user);
        // 5. 生成token
        String token = UUID.fastUUID().toString();
        // 6. 将token存入redis
        stringRedisTemplate.opsForValue().set(TOKEN_PREFIX + token, JSONUtil.toJsonStr(user), TTL, TIME_UNIT);
        // 7. 返回token
        return Result.ok(token);
    }


    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        // 1. 移除redis中的 token
        String token = request.getHeader("authorization");
        if (StrUtil.isNotBlank(token)) {
            stringRedisTemplate.delete(TOKEN_PREFIX + token);
        }
        return Result.ok();
    }
}
